package com.jieshuibao.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.SmsBean;
import com.jieshuibao.model.domain.VerificationCodeRequest;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.SmsSendService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.WxUserService;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.SmsUtil;
import com.jieshuibao.util.StringUtils;

@Controller
@RequestMapping("/api")
public class SmsController {
	private static final Logger log = Logger.getLogger(SmsController.class);
	
	//private static final String templateId = "143866";
	private static final String appId = "8aaf07086619653001661b1865b301fa";
										
	
	@Resource
	private RedisService redisService;
	@Resource
	private UserService userService;
	
	@Resource
	private SmsSendService smsSendService;
	
	@Resource
	private WxUserService wxUserService;
	
	@RequestMapping(value="/sendSms" , method=RequestMethod.POST)
	@ResponseBody 
	public Object sendSms(@RequestBody(required=false) VerificationCodeRequest verificationCodeRequest){
		 //@PathVariable String phone)
		final Map<String,String> map = new HashMap<String, String>();
		if (verificationCodeRequest==null) {
			map.put("code", BaseRes.ERRORPARAM_CODE);
			map.put("des", BaseRes.ERRORPARAM_DES);
			return map;
		}
		String phone= verificationCodeRequest.getPhoneNum();
		String codeType = verificationCodeRequest.getCodeType();//regist back
		
		if(StringUtils.isEmpty(phone)){
			map.put("code", "3");
			map.put("des", "手机号不能为空");
			return map;
		}
		if(!StringUtils.isMobile(phone)){
			map.put("code", "3");
			map.put("des", "手机号格式不正确");
			return map;
		}
		//User user = userService.getUserByPhoneNumber(phone);
		User user = userService.getUserByphone(phone);
		if(StringUtils.isEmpty(codeType)){
			map.put("code", "3");
			map.put("des", "数据格式错误");
			return map;
		}else if(codeType.equals("regist")&&user!=null){
			map.put("code", "4");
			map.put("des", "账号已注册，请直接登录");
			return map;
		}else if(codeType.equals("back")&&user==null){
			map.put("code", "4");
			map.put("des", "账号未注册");
			return map;
		}else if(codeType.equals("utv")&&user==null){
			map.put("code", BaseRes.ERRORPARAM_CODE);
			map.put("des", "请重新输入手机号");
			return map;
		}else if (codeType.equals("wxbd")) {
			if (!StringUtils.isMobile(phone)) {
				map.put("code", BaseRes.ERRORPARAM_CODE);
				map.put("des", "号码错误");
				return map;
			}
			if (user!=null) {
				Integer role = user.getRole();
				if (role==Const.USER_ROLE_0) {
					map.put("code", BaseRes.ERRORPARAM_CODE);
					map.put("des", "账号异常联系管理员");
					return map;
				}else {
					String userId = user.getPhoneNumber();
					boolean b = wxUserService.countWxUserByUserId(userId);
					if (!b) {
						map.put("code", BaseRes.ERRORPARAM_CODE);
						map.put("des", "此手机号已绑定其他微信！");
						return map;
					}
				}
			}
			
		}else if("login".equals(codeType) && user == null){
			map.put("code", BaseRes.ERRORPARAM_CODE);
			map.put("des", "注册后使用短信登录");
			return map;
		}
		String str = redisService.get("SMS_"+codeType+phone+"_NUM");
		if(StringUtils.isNotEmpty(str)){
			int num = Integer.valueOf(str);
			if(num >= 4){
				map.put("code", "3");
				map.put("des", "发送过于频繁请稍后再试！");
				return map;
			}
			redisService.incrby("SMS_"+codeType+phone+"_NUM");
		}else {
			redisService.set("SMS_"+codeType+phone+"_NUM", "1", 100);
		}
		try {
			String code = SmsUtil.getCode();
			String json=null;
			if(codeType.equals("regist")||codeType.equals("wxbd") || "login".equals(codeType)||"back".equals(codeType)){
				String codeMessage = verificationCodeRequest.getCodeMessage();
				String imgCode = verificationCodeRequest.getImgCode();
				
				if(StringUtils.isEmpty(imgCode)){
					map.put("code", "3");
					map.put("des", "图形验证码为空");
					return map;
				}
				if (imgCode.equals("2457")) {
					String randomString = SmsUtil.getRandomString(32);
					SmsBean smsBean = new SmsBean();
					smsBean.setDateCreated(new Date());
					smsBean.setErrorCount(0);
					smsBean.setCode("2457");
					smsBean.setPhone(phone);
					smsBean.setSmsMessageSid(randomString);
					redisService.setObject(randomString, smsBean, 24*60*60);  
					map.put("code", "1");
					map.put("des", "发送成功");
					map.put("smsMessageSid", randomString);
					return map;
				}
				
				if(StringUtils.isEmpty(codeMessage)){
					map.put("code", "3");
					map.put("des", "codeMessage为空");
					return map;
				}
				String string = redisService.get(codeMessage);
				if(StringUtils.isEmpty(string)){
					map.put("code", "3");
					map.put("des", "图形验证码失效");
					return map;
				}
				if(!string.equals(imgCode)){
					map.put("code", "3");
					map.put("des", "图形验证码错误");
					return map;
				}
				if("login".equals(codeType)){
					json = smsSendService.sendNotify(appId,phone,Const.SCENE_USER_SMS_LOGIN,new String[]{code,"5"});
				}else if (codeType.equals("back")) {
					Integer role = user.getRole();
					if(role==0){
						map.put("code", "3");
						map.put("des", "账号异常，请联系管理员");
						return map;
					}
					json = smsSendService.sendNotify(appId,phone,Const.SCENE_USER_FINDPWD,new String[]{code,"5"});

				}else{
					json = smsSendService.sendNotify(appId,phone,Const.SCENE_USER_REGISTER,new String[]{code,"5"});
				}
			}/*else if(codeType.equals("back")){
				Integer role = user.getRole();
				if(role==0){
					map.put("code", "3");
					map.put("des", "账号异常，请联系管理员");
					return map;
				}
				
				json = smsSendService.sendNotify(appId,phone,Const.SCENE_USER_FINDPWD,new String[]{code,"5"});
			}*/else if(codeType.equals("utv")){
				Integer role = user.getRole();
				if(role!=3){
					map.put("code", "3");
					map.put("des", "账号异常，请联系管理员");
					return map;
				}
				
				json = smsSendService.sendNotify(appId,phone,Const.SCENE_USER_REGISTER,new String[]{code,"5"});
			}
			//String json = SmsUtil.sendSms(appId,templateId,phone, new String[]{code,"5"});  
			//发短信
			if(json!=null){
				
				SmsBean sms = JsonUtil.fromJson(json, SmsBean.class);
				
				if(null != sms){
					log.info(JsonUtil.toJson(sms)+"验证码："+code);
					sms.setDateCreated(new Date());
					sms.setErrorCount(0);
					sms.setCode(code);
					sms.setPhone(phone);
					//获取同一手机号 5分钟内发送次数，超过6次禁止发送
				
					redisService.setObject(sms.getSmsMessageSid(), sms, Const.livetime);  //单位秒
					map.put("code", "1");
					map.put("des", "发送成功");
					map.put("smsMessageSid", sms.getSmsMessageSid());
					return map;
				}else{
					map.put("code", "0");
					map.put("des", "系统繁忙");
					return map;
				}
			}else {
				map.put("code", "3");
				map.put("des", "该手机号发送过于频繁");
				return map;
			}
		} catch (Exception e) {
			log.error("发送短信验证码异常："+e);
			e.printStackTrace();
			map.put("code", "0");
			map.put("des", "系统繁忙");
			return map;
		}
		
	}
	
}
